import 'package:flutter/material.dart';
import 'package:jiaju_flutter/widgets/image/comm_image.dart';

class Recommond extends StatelessWidget {
  final String label;
  final Widget options;
  final List<RecommondItem> itemList;
  final double space;
  final int rowCount;
  final Function(int index) onTap;

  const Recommond(this.label, this.itemList,
      {Key key, this.options, this.space = 10.0, this.rowCount = 2, this.onTap})
      : super(key: key);

  _buildHeader(BuildContext context) {
    var rightWidget = options;
    if (options == null) {
      rightWidget = Container();
    }
    return Container(
      margin: EdgeInsets.only(top: space),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(label),
          rightWidget,
        ],
      ),
    );
  }

  _buildContent(BuildContext context, double width) {
    return GridView.builder(
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: rowCount,
          crossAxisSpacing: space,
          mainAxisSpacing: space,
          childAspectRatio: 2,
        ),
        itemCount: itemList.length,
        itemBuilder: (BuildContext context, int index) {
          return Ink(
            color: Colors.white,
            child: InkWell(
              onTap: () => onTap(index),
              child: Container(
                padding: EdgeInsets.all(5),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Expanded(
                      child: Text(itemList[index].text),
                      flex: 1,
                    ),
                    CommImage(
                      itemList[index].img,
                      width: 40,
                      height: 40,
                    ),
                  ],
                ),
              ),
            ),
          );
        });
  }

  @override
  Widget build(BuildContext context) {
    var width = MediaQuery.of(context).size.width;
    var itemWidth = (width - space * (rowCount + 1)) / rowCount;
    return Container(
      width: width,
      margin: EdgeInsets.only(left: space, right: space),
      child: Column(
        children: [
          _buildHeader(context),
          Container(
            margin: EdgeInsets.only(top: space),
            child: _buildContent(context, itemWidth),
          ),
        ],
      ),
    );
  }
}

class RecommondItem {
  final String text;
  final String img;

  RecommondItem(this.text, this.img);
}
